define(['jquery', 'bootstrap', 'backend', 'table', 'form','backend/maputils','backend/second/househelper','backend/second/inspects','backend/second/texthelper','backend/stringutils'],
 function ($, undefined, Backend, Table, Form,map,helper,inspectsfunc,texthelper) {
    var arr=['在售','停售','已售','无效'];
    var labels=['success','primary','info','default'];
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'second/items/index' + location.search,
                    add_url: 'second/items/add',
                    edit_url: 'second/items/edit',
                    view_url: 'second/items/view',
                    del_url: 'second/items/del',
                    multi_url: 'second/items/multi',
                    table: 'second_items',
                }
            });

            var table = $("#table");
            if(!secondSort){
                secondSort ='update_time';
            }
            
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id', pageSize: 20,
                sortName: secondSort,
                sortOrder: "desc",  
                dblClickToEdit:false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'),formatter:function(value,row,index){
                            var str=value;
                            if(row.view_level>0){
                                str += " <span class='label label-warning'>私</span>";
                            }else{
                                str += " <span class='label label-default'>公</span>";
                            }
                            return str;
                        }},
                        {field: 'newhousebuilding.areaName', title:'区域',operate: 'LIKE',formatter:function(c,r){
                            if(c){
                                var _array = c.split('/');
                                return _array[_array.length-1];
                            }else{
                                return "&nbsp;";
                            }
                        }},
                        {field: 'newhousebuilding.building_name', title:'小区名称',operate: 'LIKE',formatter:function(value,row){
                            if(second_show_fanghao){
                                if(!value) value='楼盘字典异常';
                                var str = value;
                                if(row.dong) str += ' ' + row.dong;
                                if(row.shi)  str += '#' + row.shi;
                                return str;
                            }else{
                                return value;
                            }
                        }},
                        {field: 'dong', title: __('Dong'),operate: 'LIKE',visible:false},
                        {field: 'shi', title: __('Shi'),operate: 'LIKE',visible:false},
                        {field: 'shi_count', title:'房型',formatter:function(c,r){
                            return c + '室' + r.ting_count + '厅';
                        }},
                        {field: 'floor', title: __('Floor'),formatter:function(c,r){
                            return c + '/' + r.floor_total;
                        }},
                        {field: 'area', title: __('Area'), operate:'BETWEEN',formatter:function(c,r){
                            return c + ' m<sup>2</sup>';
                        }},
                        {field: 'unit_price', title:'元/平方', operate:'BETWEEN'},
                        {field: 'total_price', title: __('Total_price'), operate:'BETWEEN',formatter:function(c,r){
                            return c + '万';
                        }},
                        {field: 'customer_name', title: __('Customer_name'),operate: 'LIKE'},
                        {field: 'mobile', title: __('mobile'),operate: 'LIKE',visible:false},
                        {field: 'seconddecoration.decoration', title: __('Seconddecoration.decoration')},
                        {field: 'newhousebuildingtypes.type_name', title:'类型'},
                        {field: 'state', title:'状态',searchList: {"0":('在售'),"1":'停售',"2":'已售','3':'无效'},formatter:function(value,row,index){
                            var str= "<span class='label label-" + labels[value] + "'>" + arr[value] + "</span>";
                            return str;
                        }},
                        {field: secondSort, title: secondSortName, operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'admin.nickname', title: '录入',operate: 'LIKE'},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                        buttons:[
                            {
                                name:'view',
                                text:'查看',
                                title:'查看',
                                icon:'fa fa-building',
                                classname:'btn btn-xs btn-success btn-view btn-dialog',
                                url:'second/items/view'
                            }
                        ],formatter: Table.api.formatter.operate
                    }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            table.on('post-body.bs.table',function(){
                $("a.btn-view").data('area',["90%","95%"]);
                $("a.btn-editone").data('area',["85%","85%"]);
            });
            table.on('dbl-click-row.bs.table', function (e, row, element, field) {
                $(".btn-view", element).trigger("click");
            });
        },
        add: function () {
            var me=this;
            // 自动计算总价
            $("#c-area,#c-unit_price").change(function(){
                me.calcPrice();
            });
            $("#c-total_price").change(function(){
                me.calcUnitPrice();
            });
            $("#c-building_id").change(function(){
                me.getBuildingAddress();
            });
            $("#c-dong,#c-shi").change(function(){
                me.checkExistsDongShi();
            });
         
            $("#c-mobile").change(function(){
                me.checkExistsMobile();
            });
            $("#t-mem").change(function(){
               me.autoFillMulti($(this).val());
            });
            $("#btnAutofill").click(function(){
                var line = texthelper.getLineNum($("#t-mem"));
                var content = texthelper.selectRow($("#t-mem"),line);
                me.autoFill(content);
            });
            // 触发自动评估
            $("#c-floor,#c-floor_total,#c-area,#c-build_year,#c-shi_count,#c-ting_count,#c-decoration_id,#c-type_id").change(function(){
                me.predict();
            });
            $("#btnPredict").click(function(){
                me.predict();
            });
            // 法拍房选项控制 
            $("#c-is_auction").click(function(){
                if($(this).prop('checked')){
                    $(".show-with-auction").show();
                    if($("#c-total_price").val() && !$("#c-auction_price").val()){
                        $("#c-auction_price").val($("#c-total_price").val());
                    }
                }else
                    $(".show-with-auction").hide();
            });
            if(show_auction) 
                $(".show-with-auction").show();
            else
                $(".show-with-auction").hide();
            Controller.api.bindevent();
           
        },
        /// 预测
        predict:function(){
            // $areaCode,$shiCount,$tingCount,$area,$floor,$floorTotal,$typeId,$decorationId,$metroCount,$buildYear,$sellDate
            var areaCode = $("#c-building_areaCode").val();
            var shiCount = $("#c-shi_count").val();    if(!shiCount)shiCount=1;
            var tingCount = $("#c-ting_count").val();  if(!tingCount)tingCount=2;
            var area     = $("#c-area").val();
            var floor    = $("#c-floor").val();        if(!floor)floor=1;
            var floor_total=$("#c-floor_total").val(); if(!floor_total)floor_total=6;
            var type_id  = $("#c-type_id").val();
            var decoration_id = $("#c-decoration_id").val();
            var metroCount = 0;                        
            var buildYear = $("#c-build_year").val();  if(!buildYear || buildYear=='0')buildYear=(new Date()).getFullYear()-6;
            var sellDate  = (new Date()).format("yyyy-MM-dd");
            console.log(areaCode , shiCount , area , floor , floor_total ,  buildYear , sellDate);
            if(areaCode && shiCount && area && floor && floor_total &&  buildYear && sellDate){
                $.get("assessment/prereport/predict",{"areaCode": areaCode ,
                    "shiCount":shiCount ,
                    "tingCount":tingCount,
                    "area":area,
                    "floor":floor,
                    "floorTotal":floor_total,
                    "decorationId":decoration_id,
                    "typeId" : type_id,
                    "metroCount":metroCount,
                    "buildYear":buildYear,
                    "sellDate":sellDate },function(ret){
                        if(ret.success){
                            $("#txtPriceAssessment").text(ret.result.toFixed(1) + ' 万元');
                        }
                });
            }
        },
        edit: function () {
           return this.add();
        },

        /**
         * 多行批量录入
         */
        autoFillMulti:function(val){
            $textBox = $("#t-mem");
            var array = texthelper.removeBlank($textBox);
            if(array.length>1){
                $("#btnAutofill").css("display","block");
            }
            // 改变文本框高度
            var lineheight = parseInt($textBox.css('line-height')) + 12 ;

            $textBox.css("height",lineheight * (array.length>1?7:1));
            
            if(array[0]){
                texthelper.selectRow($textBox,1);
                this.autoFill(array[0]);
            }
        },
        // 自动填充
        autoFill:function(val){
            console.log('autofill val',val);
            var me=this;
            var ret = helper.analysisInfo(val);
            if(ret.shiCount)        $("#c-shi_count").val(ret.shiCount);
            if(ret.tingCount)       $("#c-ting_count").val(ret.tingCount);
            if(ret.dong)            $("#c-dong").val(ret.dong);
            if(ret.shi)             $("#c-shi").val(ret.shi);
            if(ret.customerName)    $("#c-customer_name").val(ret.customerName);
            if(ret.area)            $("#c-area").val(ret.area);
            if(ret.priceTotal)      $("#c-total_price").val(ret.priceTotal);
            if(ret.floor)           $("#c-floor").val(ret.floor);
            if(ret.floorTotal)      $("#c-floor_total").val(ret.floorTotal);
            if(ret.mobile)         {
                $("#c-mobile").val(ret.mobile);
                me.checkExistsMobile();
            } 
            if(ret.decoration){
                $("#c-decoration_id").val(ret.decoration);
                $("#c-decoration_id").selectPageRefresh();
            }
            if(ret.buildingName){
                $.post('second/buildings/getBuilding',{buildingName:ret.buildingName},function(res){
                    if(res.id){
                        $('#c-building_id').val(res.id);
                        $('#c-building_id').selectPageRefresh();
                        me.getBuildingAddress();
                        if(ret.dong && !ret.floorTotal && !$("#c-floor_total").val()){
                            $.get('second/items/getFloorTotal',{building_id:res.id,dong:ret.dong},function(retFloor){
                                $("#c-floor_total").val(retFloor.floorTotal);
                            });
                        }

                    }
                });
            }
            me.calcPrice();
        },
        getBuildingAddress:function(){
            var me=this;
            // 获取地址
            if( $("#c-building_id").val()){
               $.get('second/buildings/getAddress',{ids:$("#c-building_id").val()},function(ret){
                   console.log('ret building address',ret);
                   $("#c-address").val(ret.address);
                   $("#c-building_areaCode").val(ret.areaCode).selectPageRefresh();
                   me.checkExistsDongShi();
               });
           }
       },
        /**
         * 判断房源是否存在
         */
        checkExistsDongShi:function(){
            $("#ulDuplicateDongShi").empty();
            if($("#c-building_id").val() && $("#c-dong").val() &&  $("#c-shi").val()){
                $.post('second/items/checkExistsDongShi',{building_id:$("#c-building_id").val(),dong:$("#c-dong").val(),shi:$("#c-shi").val()},function(r){
                    if(r.exists){
                        Toastr.error('房源已经存在');
                        var str= ' <span >编号 : ' + r.id + '</span> ';
                        str += ' <span>号码:' + r.mobile + '</span> <a href="second/items/view/ids/' + r.id 
                        + '" class="btn-view btn-dialog" title="查看" data-table-id="table" data-field-index="17" data-row-index="0" data-button-index="0">' 
                        + ' <i class="fa fa-building"></i> 查看 </a>';
                        $("#ulDuplicateDongShi").append('<li class="list-group-item">' + str + '</li>');
                    }else if(r.msg){
                        Toastr.error('没有权限检查房源是否存在')
                    }
                    else{
                        $("#ulDuplicateDongShi").append('<li class="list-group-item">没有重复房源,允许录入</li>');
                    }
                });
            }
            // 如果所在层没有值，就自动填充
            var _shi = $("#c-shi").val();
            if(_shi && !$("#c-floor").val()){
                if(_shi.length>=3 && _shi.length<=4){
                    var _floor = _shi.substring(0,_shi.length-2);
                    $("#c-floor").val(_floor);
                }
            }
            // 如果没有总层数，从服务器读取
            if($("#c-dong").val() && $("#c-building_id").val() && !$("#c-floor_total").val() ){
                $.get('second/items/getFloorTotal',{building_id:$("#c-building_id").val(),dong:$("#c-dong").val()},function(retFloor){
                    $("#c-floor_total").val(retFloor.floorTotal);
                });
            }
        },
        checkExistsMobile:function(){
            $("#ulDuplicateMobile").empty();
            if($("#c-mobile").val()){
                $.post('second/items/checkExistsMobile',{mobile:$("#c-mobile").val()},function(r){
                    if(r.exists){
                        Toastr.error('该号码登记过房源');
                        var str='';
                        for(var i in r.ids){
                            str += "<li class='list-group-item'>";
                            str += ' <span >编号 : ' + r.ids[i].id + '</span>';
                            str += ' <span>' + r.ids[i].building_name + '</span>';
                            str += ' <span>' + r.ids[i].dong + '</span>#<span>' + r.ids[i].shi + '</span>';
                            str += ' <a href="second/items/view/ids/' 
                                + r.ids[i].id 
                                + '" class="btn-view btn-dialog" title="查看" data-table-id="table" data-field-index="17" data-row-index="0" data-button-index="0">' 
                                + ' <i class="fa fa-building"></i> 查看 </a>';
                            str += "</li>";
                        }
                        
                        $("#ulDuplicateMobile").append(str);
                    }else if(r.msg){
                        Toastr.error('没有权限检查房源是否存在')
                    }else{
                        $("#ulDuplicateMobile").append('<li class="list-group-item">没有重复房源</li>');
                    }
                });
            }
        },
        /**
         * 计算价格
         */
        calcPrice:function(){
            var area=parseFloat($("#c-area").val());
            var unit=parseFloat($("#c-unit_price").val());
            var total=parseFloat($("#c-total_price").val());
            if(area&&unit&&!total){$("#c-total_price").val(area*unit/10000)};
            if(area&&total&&!unit){$("#c-unit_price").val((total*10000/area).toFixed(2))};
        },
        /**
         * 重算单价
         */
        calcUnitPrice:function(){
            var area=parseFloat($("#c-area").val());
            var total=parseFloat($("#c-total_price").val());
            var newUnit=(total*10000/area).toFixed(2);
            if(newUnit!=$("#c-unit_price").val()){
                $("#c-unit_price").val((total*10000/area).toFixed(2));
            }
        },
        view:function(){
            var html="<span class='label label-" + labels[state] + "'>" + arr[state] + "</span>";
            $("#tdState").html(html);
            //TODO: 地址
            if(lat && lng){
                map.init("map-container",lng,lat,function(e){
                    map.getLocation({lat:lat,lng:lng},function(result){
                        if(result){
                            $("#c-address").text(result.address); 
                        }
                    });
                });
            }else{
                map.init("map-container",117.17,31.52,function(e){
                    map.geo(building,function(point,ret){
                            
                    });
                });
               
            }
            renderFollow();
         
            function renderFollow(){
                console.info('加载跟进');
                // 加载跟进
                $.post('second/follow',{item_id:item_id}, function(data, ret){
                    //成功的回调
                    var value=data.rows;
                    $("#ulFollow").empty();
                    var state;
                    for(var i=0;i<value.length;i++){
                        var tmp=value[i];
                        if(i==0)state=tmp.state;
                        var str='<li>[' + tmp.create_time + ']';
                        str +='[ '+arr[ tmp.state] + ' ]';
                        str += tmp.comment;
                        str += ' [ ' + tmp.admin.nickname + ' ] ';
                        str+='</li>';
                        $("#ulFollow").append(str);
                    }
                    if(state){
                        var html="<span class='label label-" + labels[state] + "'>" + arr[state] + "</span>";
                        $("#tdState").html(html);
                    }
                    return false;
                 });
            }
            $("#btnNewFollow").click(function(){
                Fast.api.open("second/follow/add?item_id=" + item_id + '&state=' + state, '新增跟进', {
                    callback: function (data) {
                        renderFollow();
                    }
                });
                return false;
            });
            Controller.api.bindevent();
        },
        inspects:inspectsfunc.list,
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"), function(data, ret){
                        Toastr.success(data);//成功
                        
                        $("#c-address").val('');
                        $("#c-dong").val('');
                        $("#c-shi").val('');
                        $("#c-shi_count").val('');
                        $("#c-ting_count").val('');
                        $("#c-area").val('');
                        $("#c-build_year").val('');
                        $("#c-unit_price").val('');
                        $("#c-total_price").val('');
                        $("#c-floor").val('');
                        $("#c-floor_total").val('');
                        $("#c-customer_name").val('');
                        $("#c-mobile").val('');

                        var next=texthelper.moveNextRow($("#t-mem"));
                        if(next){
                            Controller.autoFill(next);
                            return false;
                        }else{
                            return true;
                        }
                        
                    }, function(data, ret){
                        
                        Toastr.error(ret.msg);
                        var next=texthelper.moveNextRow($("#t-mem"));
                        if(next){
                            Controller.autoFill(next);
                            return false;
                        }else{
                            return true;
                        }
                    }, function(success, error){
                        
                        //bindevent的第三个参数为提交前的回调
                        //如果我们需要在表单提交前做一些数据处理，则可以在此方法处理
                        //注意如果我们需要阻止表单，可以在此使用return false;即可
                        //如果我们处理完成需要再次提交表单则可以使用submit提交,如下
                        //Form.api.submit(this, success, error);
                        //return false;
                        var auction_time=$("#c-auction_time").val();
                        console.log('auction_time',auction_time);
                        if(auction_time){
                            var _array = auction_time.split(' - ');
                            $("#c-auction_time_start").val(_array[0]);
                            $("#c-auction_time_end").val(_array[1]);
                        }else{
                            $("#c-auction_time_start").val('');
                            $("#c-auction_time_end").val('');
                        }
                    });
            }
        }
    };
    return Controller;
});